package com.guaoran.distributed.io.nio.one.buffer;

import java.nio.ByteBuffer;

/**
 * @Author gucheng
 * @Description Buffer slice()
 * 2019-04-19 10:12
 */
public class BufferSliceDemo {
    static public void main( String args[] ) throws Exception {  
        ByteBuffer buffer = ByteBuffer.allocate( 10 );  
          
        // 缓冲区中的数据0-9  
        for (int i=0; i<buffer.capacity(); ++i) {  
            buffer.put( (byte)i );  
        }  
          
        System.out.println(buffer);
        // 创建子缓冲区
        buffer.position(3);
        buffer.limit(7);
        System.out.println(buffer);
        ByteBuffer slice = buffer.slice();
        System.out.println(slice);
        // 改变子缓冲区的内容
        for (int i=0; i<slice.capacity(); ++i) {  
            byte b = slice.get( i );  
            b *= 10;  
            slice.put( i, b );  
        }
        System.out.println("slice \t\t"+slice);
        System.out.println("buffer \t\t"+buffer);

        buffer.position(0);
        buffer.limit( buffer.capacity() );
        System.out.println("buffer \t\t"+buffer);

        while (buffer.remaining()>0) {  
            System.out.print(buffer.get()+"\t");
        }  
    }  
}  
